<template>
  <div>
    <el-breadcrumb separator-class='el-icon-arrow-right'>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <el-card>
      <el-row :gutter='20'>
        <el-col :span='20'>
          <el-input placeholder='请输入内容' clearable ref='search' @clear='getUserList' v-model='userInfo.query'>
            <el-button slot='append' icon='el-icon-search' @click='getUserList'></el-button>
          </el-input>
        </el-col>
        <el-col :span='4'>
          <el-button type='primary' @click='dialogVisible = true'>添加用户</el-button>
          <el-dialog
            title='添加用户'
            center
            @close='addFormClose'
            :visible.sync='dialogVisible'
            width='50%'>
            <!--            新增用户表单-->
            <el-form :model='addForm' label-width='80px' :rules='addFormRules' ref='addFormRef'>
              <el-form-item label='用户名' prop='username'>
                <el-input v-model='addForm.username'></el-input>
              </el-form-item>
              <el-form-item label='密码' prop='password'>
                <el-input type='password' v-model='addForm.password' show-password></el-input>
              </el-form-item>
              <el-form-item label='邮箱' prop='email'>
                <el-input v-model='addForm.email'></el-input>
              </el-form-item>
              <el-form-item label='电话' prop='mobile'>
                <el-input v-model.number='addForm.mobile'></el-input>
              </el-form-item>
            </el-form>
            <span slot='footer' class='dialog-footer'>
    <el-button @click='dialogVisible = false'>取 消</el-button>
    <el-button type='primary' @click='addUserInfo'>确 定</el-button>
  </span>
          </el-dialog>
        </el-col>
      </el-row>
      <!-- 用户表格-->
      <el-table :data='userList' style='width: 100%' border stripe>
        <el-table-column type='index' label='#' align='center'></el-table-column>
        <el-table-column prop='username' label='姓名' align='center'></el-table-column>
        <el-table-column prop='email' label='邮箱' align='center'></el-table-column>
        <el-table-column prop='mobile' label='电话' align='center'></el-table-column>
        <el-table-column prop='role_name' label='角色' align='center'></el-table-column>
        <el-table-column label='状态' align='center'>
          <template v-slot='scope'>
            <el-switch
              v-model='scope.row.mg_state'
              active-color='#13ce66'
              @change='userState(scope.row)'
              inactive-color='#cccccc'>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label='操作' width='200px' align='center'>
          <template v-slot='scope'>
            <el-button type='primary' icon='el-icon-edit' size='mini'
                       @click='updateUserInfo(scope.row)'>
            </el-button>
            <el-button type='danger' slot='reference' icon='el-icon-delete' size='mini'
                       @click='delUserInfo(scope.row.id)'></el-button>
            <el-tooltip class='item' effect='dark' content='设置' :enterable='false' placement='top'>
              <el-button type='warning' icon='el-icon-setting' size='mini' @click='assignRole(scope.row)'></el-button>
            </el-tooltip>

            <!-- 修改用户信息弹出层-->
            <el-dialog
              title='修改用户信息'
              :visible.sync='updateUserVisible'
              center
              width='50%'>
              <el-form ref='updateFormRef' :rules='addFormRules' :model='updateForm' label-width='90px'>
                <el-form-item label='用户名'>
                  <el-input v-model='updateForm.username' :disabled='true'></el-input>
                </el-form-item>
                <el-form-item label='邮箱' prop='email'>
                  <el-input v-model='updateForm.email'></el-input>
                </el-form-item>
                <el-form-item label='手机号' prop='mobile'>
                  <el-input v-model.number='updateForm.mobile'></el-input>
                </el-form-item>
              </el-form>
              <span slot='footer' class='dialog-footer'>
    <el-button @click='updateUserVisible = false'>取 消</el-button>
    <el-button type='primary' @click='updateUser'>确 定</el-button>
  </span>
            </el-dialog>
            <!-- 删除用户信息-->
            <el-dialog
              :visible.sync='delUserVisible'
              :show-close='false'
              width='40%'>
              <i class='el-icon-question'>是否删除该用户</i>
              <span slot='footer' class='dialog-footer'>
    <el-button @click='delUserVisible = false' size='mini'>取 消</el-button>
    <el-button type='primary' @click='delUser' size='mini'>确 定</el-button>
  </span>
            </el-dialog>
            <!-- 用户分配角色-->
            <el-dialog
              title='分配用户角色'
              center
              :visible.sync='userRoleVisible'
              width='50%'
              class='user-role'
              @close='resetSelect'>
              <p>用户名称: <b>{{ userRoleInfo.username }}</b></p>
              <p>用户角色: <b>{{ userRoleInfo.role_name }}</b></p>
              <p>选择角色:
                <span>
                  <el-select v-model='changeRole' placeholder='请选择角色'>
                    <el-option v-for='item in allRoleList'
                               :key='item.id'
                               :label='item.roleName'
                               :value='item.id'>
                    </el-option>
                  </el-select>
                </span></p>
              <span slot='footer' class='dialog-footer'>
    <el-button @click='userRoleVisible = false' size='mini'>取 消</el-button>
    <el-button type='primary' @click='setRole(userRoleInfo.id)' size='mini'>确 定</el-button>
  </span>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
      <el-divider></el-divider>
      <!--      分页-->
      <el-pagination
        @size-change='handleSizeChange'
        @current-change='handleCurrentChange'
        :current-page='userInfo.pagenum'
        :page-sizes='[1, 2, 3, 5, 10,15]'
        :page-size='userInfo.pagesize'
        layout='total, sizes, prev, pager, next, jumper'
        :total='total'>
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 自定义校验手机号
    const checkMobile = (rule, value, callback) => {
      const Reg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (Reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      userList: [],
      total: 0,
      userInfo: {
        query: '',
        pagenum: 1,
        pagesize: 3
      },
      dialogVisible: false,
      addForm: {
        username: '',
        email: '',
        mobile: '',
        password: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 3, max: 8, message: '用户名在3-8个字符之间', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名在6-15个字符之间', trigger: 'blur' }
        ],
        mobile: [
          { type: 'number', message: '电话必须为数字值', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      updateUserVisible: false,
      updateForm: {},

      delUserVisible: false,
      delUserId: '',
      setUserVisible: false,
      // 分配角色框的显示
      userRoleVisible: false,
      // 分配角色的用户信息
      userRoleInfo: {},
      // 所有角色列表
      allRoleList: [],
      // 被选择的分配角色
      changeRole: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户信息列表
    async getUserList() {
      const { data: user } = await this.$http.get('users', { params: this.userInfo })
      if (user.meta.status !== 200) {
        return this.$msg.error(user.meta.msg)
      }
      this.userList = user.data.users
      this.total = user.data.total
    },
    // 监听switch用户状态
    async userState(val) {
      const { data: res } = await this.$http.put(`users/${ val.id }/state/${ val.mg_state }`)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$msg.error('更新数据失败')
      }
      this.$msg.success('更新用户状态成功')
    },
    // 监听每页显示条数
    handleSizeChange(val) {
      this.userInfo.pagesize = val
      this.getUserList()
    },
    // 监听当前页
    handleCurrentChange(val) {
      this.userInfo.pagenum = val
      this.getUserList()
    },
    // 添加用户
    addUserInfo() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$msg.error('添加用户失败')
        }
        this.dialogVisible = false
        this.$msg.success(res.meta.msg)
        await this.getUserList()
      })
    },
    // 重置添加用户表单
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 修改用户信息
    updateUserInfo(data) {
      this.updateUserVisible = true
      this.updateForm = data
    },
    // 发起请求，更新信息
    async updateUser() {
      const { data: res } = await this.$http.put(`users/${ this.updateForm.id }`, this.updateForm)
      if (res.meta.status !== 200) {
        return this.$msg.error('修改用户信息失败')
      }
      this.$msg.success('修改用户信息成功')
      this.updateUserVisible = false
    },
    // 拉起用户信息显示框
    delUserInfo(id) {
      this.delUserId = id
      this.delUserVisible = true
    },
    // 删除用户信息
    async delUser() {
      const { data: res } = await this.$http.delete('users/' + this.delUserId)
      if (res.meta.status !== 200) {
        return this.$msg.error('删除用户失败')
      }
      this.$msg.success(res.meta.msg)
      this.delUserVisible = false
      await this.getUserList()
    },
    // 点击拉起配分角色框
    async assignRole(data) {
      this.roleId = data.id
      this.userRoleInfo = data
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$msg.error('获取角色列表失败')
      }
      this.allRoleList = res.data
      this.userRoleVisible = true
    },
    // 用户分配角色
    async setRole(id) {
      if (!this.changeRole) {
        return this.$msg.error('请选择用户角色')
      }
      const { data: res } = await this.$http.put(`users/${ id }/role`, { rid: this.changeRole })
      if (res.meta.status !== 200) {
        return this.$msg.error('分配用户角色失败')
      }
      this.$msg.success('用户角色分配成功')
      this.getUserList()
      this.userRoleVisible = false
    },
    // 关闭分配框后，重置信息
    resetSelect() {
      this.changeRole = ''
    }
  }
}
</script>

<style lang='less' scoped>
.el-select {
  width: 80%;
}

.el-table {
  margin-top: 20px;
  font-family: "楷体", serif;
  border-radius: 5px;
}

.el-pagination {
  text-align: center;
}

.el-icon-question {
  color: #ff0000;
  font-size: 18px;
}

.user-role {
  b {
    color: #00b7ee;
    font-size: 16px;
    letter-spacing: .2em;
  }
}
</style>
